package com.ap.core.xml.datatype.converter;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;

import javax.xml.bind.DatatypeConverter;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 * Custom XML date time conversion for JAXB binding.
 */
public class XMLDateTimeTypeConverter {

    private static final DatatypeFactory DATA_TYPE_FACTORY;

    static {
        try {
            DATA_TYPE_FACTORY = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException e) {
            throw new AssertionError(e);
        }
    }

    private XMLDateTimeTypeConverter() {
        super();
    }

    /**
     * Marshal localData to XMLdateTime lexical representation.
     *
     * @param localDateTime- local date Time
     * @return lexical xml date time
     */
    public static String printDateTime(LocalDateTime localDateTime) {
        return DatatypeConverter.printDateTime(new DateTime(localDateTime.getYear(), localDateTime.getMonthOfYear(),
                localDateTime.getDayOfMonth(), localDateTime.getHourOfDay(), localDateTime.getMinuteOfHour(),
                localDateTime.getSecondOfMinute(), 0).toGregorianCalendar());
    }

    /**
     * Convert Lexical xmlDate time string to local date.
     *
     * @param lexicalXSDDateTime - lexical XML date time, which may contains white spaces according to specs.
     * @return local date  time
     */
    public static LocalDateTime parseDateTime(String lexicalXSDDateTime) {
        XMLGregorianCalendar xmlCal = DATA_TYPE_FACTORY.newXMLGregorianCalendar(StringUtils
                .deleteWhitespace(lexicalXSDDateTime));
        return new LocalDateTime(xmlCal.toGregorianCalendar().getTimeInMillis());
    }

}
